package com.neouton.crm.op.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.Constants;
import com.neouton.crm.op.entity.SalesOpportunityVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * mybatis+ 机会点查询条件构造
 */
public final class QueryWrapperGenerator {
    /**
     * 基本查询条件及高级查询条件构造
     *
     * @param searchModel
     * @return
     */
    public static QueryWrapper<SalesOpportunityVO> opQueryWrapper(SalesOpportunityVO searchModel) {
        QueryWrapper<SalesOpportunityVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(notEmpty(searchModel.getOpportunityNumber()),
                "opportunity_number", escapeStr(searchModel.getOpportunityNumber()));
        queryWrapper.like(notEmpty(searchModel.getOpportunityTheme()),
                "opportunity_theme", escapeStr(searchModel.getOpportunityTheme()));
        queryWrapper.like(notEmpty(searchModel.getCustomerName()),
                "customer_name", escapeStr(searchModel.getCustomerName()));
        queryWrapper.like(notEmpty(searchModel.getCustomerContact()),
                "customer_contact", escapeStr(searchModel.getCustomerContact()));
        queryWrapper.like(notEmpty(searchModel.getCustomerPhone()),
                "customer_phone", escapeStr(searchModel.getCustomerPhone()));

        queryWrapper.eq(Objects.nonNull(searchModel.getOpportunityState()),
                "opportunity_state", searchModel.getOpportunityState());
        queryWrapper.eq(Objects.nonNull(searchModel.getStageStateId()),
                "stage_state_id", searchModel.getStageStateId());
        queryWrapper.eq(Objects.nonNull(searchModel.getAuditState()),
                "audit_state", searchModel.getAuditState());

        queryWrapper.in(Objects.nonNull(searchModel.getCustomerIds()) && searchModel.getCustomerIds().size() > 0, "customer", searchModel.getCustomerIds());
        queryWrapper.in(Objects.nonNull(searchModel.getOwnerIds()) && searchModel.getOwnerIds().size() > 0, "owner", searchModel.getOwnerIds());
        queryWrapper.in(Objects.nonNull(searchModel.getStageStateIds()) && searchModel.getStageStateIds().size() > 0, "stage_state_id", searchModel.getStageStateIds());
        queryWrapper.in(Objects.nonNull(searchModel.getOpportunityPossibilities()) && searchModel.getOpportunityPossibilities().size() > 0, "opportunity_possibility", searchModel.getOpportunityPossibilities());
        queryWrapper.in(Objects.nonNull(searchModel.getAuditStates()) && searchModel.getAuditStates().size() > 0, "audit_state", searchModel.getAuditStates());
        queryWrapper.in(Objects.nonNull(searchModel.getOpportunityStates()) && searchModel.getOpportunityStates().size() > 0, "opportunity_state", searchModel.getOpportunityStates());

        queryWrapper.between(Objects.nonNull(searchModel.getDiscoveryTimeStart())
                        && Objects.nonNull(searchModel.getDiscoveryTimeEnd()),
                "discovery_time", searchModel.getDiscoveryTimeStart(), searchModel.getDiscoveryTimeEnd());
        queryWrapper.between(Objects.nonNull(searchModel.getExpectedSigningDateStart())
                        && Objects.nonNull(searchModel.getExpectedSigningDateEnd()),
                "expected_signing_date", searchModel.getExpectedSigningDateStart(), searchModel.getExpectedSigningDateEnd());

        // 停留时间范围
        queryWrapper.between(Objects.nonNull(searchModel.getStageStayTimeMin())
                        && Objects.nonNull(searchModel.getStageStayTimeMax()),
                "stage_stay_time", searchModel.getStageStayTimeMin(), searchModel.getStageStayTimeMax());
        queryWrapper.ge(Objects.isNull(searchModel.getStageStayTimeMax())
                        && Objects.nonNull(searchModel.getStageStayTimeMin()),
                "stage_stay_time", searchModel.getStageStayTimeMin());
        queryWrapper.le(Objects.isNull(searchModel.getStageStayTimeMin())
                        && Objects.nonNull(searchModel.getStageStayTimeMax()),
                "stage_stay_time", searchModel.getStageStayTimeMax());

        // 预期金额范围
        queryWrapper.between(Objects.nonNull(searchModel.getExpectedAmountMin())
                        && Objects.nonNull(searchModel.getExpectedAmountMax()),
                "expected_amount", searchModel.getExpectedAmountMin(), searchModel.getExpectedAmountMax());
        queryWrapper.ge(Objects.isNull(searchModel.getExpectedAmountMax())
                        && Objects.nonNull(searchModel.getExpectedAmountMin()),
                "expected_amount", searchModel.getExpectedAmountMin());
        queryWrapper.le(Objects.isNull(searchModel.getExpectedAmountMin())
                        && Objects.nonNull(searchModel.getExpectedAmountMax()),
                "expected_amount", searchModel.getExpectedAmountMax());

        // 创建时间范围
        queryWrapper.between(Objects.nonNull(searchModel.getCreateDataTimeStart())
                        && Objects.nonNull(searchModel.getCreateDataTimeEnd()),
                "create_data_time", searchModel.getCreateDataTimeStart(), searchModel.getCreateDataTimeEnd());

        // 前端排序
        if (searchModel.getOrder() != null){
            if (Objects.equals(searchModel.getOrder(), "ascending")){   // 升序
                queryWrapper.orderByAsc(StringUtils.camelToUnderline(searchModel.getOrderByProp()));
            }else {     // 降序
                queryWrapper.orderByDesc(StringUtils.camelToUnderline(searchModel.getOrderByProp()));
            }
        }


        return queryWrapper;
    }

    // 根据机会状态全查
    public static QueryWrapper<SalesOpportunityVO> opStateQueryWrapper(SalesOpportunityVO param) {
        QueryWrapper<SalesOpportunityVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(param.getOpportunityState() != null, "opportunity_state", param.getOpportunityState());
//        queryWrapper.eq("audit_state", Constants.OPPORTUNITY_AUDIT_PASS);
        queryWrapper.like(notEmpty(param.getOpportunityTheme()), "opportunity_theme", escapeStr(param.getOpportunityTheme()));
        return queryWrapper;
    }

    public static boolean notEmpty(String str) {
        return str != null && !str.trim().isEmpty();
    }

    public static String escapeStr(String str) {
        if (!StringUtils.isEmpty(str)) {
            str = str.replaceAll("\\\\", "\\\\\\\\");
            str = str.replaceAll("_", "\\\\_");
            str = str.replaceAll("%", "\\\\%");
        }
        return str;
    }

    /**
     * 待办列表查询条件
     *
     * @param op
     * @param toDos
     * @return
     */
    public static QueryWrapper<SalesOpportunityVO> opTodoListQueryWrapper(SalesOpportunityVO op, List<ActivitiVO> toDos) {
        QueryWrapper<SalesOpportunityVO> queryWrapper = new QueryWrapper<>();
        List<Integer> toDosId = new ArrayList<>();
        toDos.forEach(item -> toDosId.add(item.getBusinessId()));
        if (toDos.size() > 0){
            queryWrapper.in("business_id", toDosId);
        }else {
            queryWrapper.apply("1=0");
        }

        queryWrapper.like(notEmpty(op.getOpportunityNumber()), "opportunity_number", op.getOpportunityNumber());
        queryWrapper.like(notEmpty(op.getOpportunityTheme()), "opportunity_theme", op.getOpportunityTheme());

        // 前端排序
        if (op.getOrder() != null){
            if (Objects.equals(op.getOrder(), "ascending")){   // 升序
                queryWrapper.orderByAsc(StringUtils.camelToUnderline(op.getOrderByProp()));
            }else {     // 降序
                queryWrapper.orderByDesc(StringUtils.camelToUnderline(op.getOrderByProp()));
            }
        }

        queryWrapper.orderByDesc("create_data_time");
        return queryWrapper;
    }
}
